//
//  MyHeaderView.swift
//  Preferential
//
//  Created by Fineland on 2021/3/8.
//

import UIKit

class MyHeaderView: UIView {
    
    //头像图片
    private(set) var hdImageView: UIKImageView!
    //基本信息
    private(set) var infoTextLabel: UILabel!
    //背景
    private var bgLayer: CAGradientLayer!
    
    //闭包
    typealias ReturnClosure = (_ typeIndex: Int) -> Void
    //回调
    var operationClosure: ReturnClosure?

    override init(frame: CGRect) {
        super.init(frame: frame)

        //创建视图
        setupViews(in: frame.size)
        //添加事件
        let recognizer = UITapGestureRecognizer(target: self, action: #selector(selectRecognizer(_:)))
        hdImageView.addGestureRecognizer(recognizer)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    private func setupViews(in size: CGSize) -> Void {
        
        //背景
        bgLayer = CAGradientLayer()
        bgLayer.frame = CGRect(x: 0.0, y: size.height - NSKVar.kScreenHeight, width: frame.size.width,
                               height: NSKVar.kScreenHeight)
        bgLayer.colors = [UIColor.fromHex(0x6FB7FF).cgColor, UIColor.fromHex(0x3698FB).cgColor]
        bgLayer.locations = [0, 1]
        bgLayer.startPoint = CGPoint(x: 0.5, y: 1)
        bgLayer.endPoint = CGPoint(x: 0, y: 0)
        //大小
        let whImg: CGFloat = ceil(0.56 * size.height)
        let hInfo: CGFloat = 44.0
        //头像
        hdImageView = UIKImageView(frame: CGRect(x: 0.5 * (size.width - whImg), y: 0.0, width: whImg, height: whImg))
        hdImageView.image = UIImage(named: "system_head_default")
        hdImageView.layer.cornerRadius = 0.5 * whImg
        hdImageView.layer.borderColor = UIColor.white.cgColor
        hdImageView.layer.borderWidth = 1.0
        hdImageView.layer.masksToBounds = true
        hdImageView.isUserInteractionEnabled = true
        //姓名
        infoTextLabel = UILabel(frame: CGRect(x: 0.0, y: hdImageView.frame.maxY, width: size.width, height: hInfo))
        infoTextLabel.font = UIFont.systemFont(ofSize: 18.0)
        infoTextLabel.textAlignment = .center
        infoTextLabel.textColor = UIColor.white
        //添加
        self.layer.addSublayer(bgLayer)
        self.addSubview(hdImageView)
        self.addSubview(infoTextLabel)
    }
    
    @objc private func selectRecognizer(_ sender: UITapGestureRecognizer) -> Void {
     
        //回调是否为空？
        if let returnClosure = self.operationClosure {
            returnClosure(1)
        }
    }
}
